<?php

namespace app\api\controller\Appoint;

use app\api\controller\Common;
use app\api\Logic\Campusclass\CampusClassCourseArrangingLogic;
use app\api\Logic\Campusclass\CampusClassCourseSignLogic;
use app\api\Logic\Campusclass\CampusClassDateRecordLogic;
use app\api\Logic\Campusclass\CampusClassLogic;
use app\api\Logic\Campusclass\CampusClassTeacherSettingLogic;
use app\api\Logic\Course\ManagementLogic;
use app\api\Logic\ManystoreLogic;
use app\api\Logic\ManystoreShopSettingLogic;
use app\api\model\CampusClassCourseSignModel;
use app\api\model\CampusClassModel;
use think\Db;
use think\Exception;

/**
 * 一对一约课接口
 */
class OneOnOneCourse extends Common
{
    protected $noNeedLogin = ['*'];

    protected $campusClassLogic;
    protected $managementLogic;
    protected $manysotreLogic;
    protected $campusClassTeacherSettingLogic;
    protected $manystoreShopSettingLogic;
    protected $campusClassDateRecordLogic;
    protected $campusClassCourseSignLogic;
    protected $campusClassCourseArrangingLogic;

    public function _initialize()
    {
        parent::_initialize();
        $this->campusClassLogic = new CampusClassLogic();
        $this->managementLogic = new ManagementLogic();
        $this->manysotreLogic = new ManystoreLogic();
        $this->campusClassTeacherSettingLogic = new CampusClassTeacherSettingLogic();
        $this->manystoreShopSettingLogic = new ManystoreShopSettingLogic();
        $this->campusClassDateRecordLogic = new CampusClassDateRecordLogic();
        $this->campusClassCourseSignLogic = new CampusClassCourseSignLogic();
        $this->campusClassCourseArrangingLogic = new CampusClassCourseArrangingLogic();
    }

    /**
     * 获取一对一可约课程
     */
    public function getCourse(){
        if($this->request->isPost()){
            $params = $this->request->param();
            //验证数据
            $params = $this->verifyData($params);

            //获取班级列表
            $list = CampusClassModel::where('shop_id',$params['shop_id'])
                ->where('class_type',2)
                ->with([
                    'courseInfo' => function ($query) {
                        $query->withField('id,name');
                    }
                ])
                ->field('id,shop_id,name,course_id,teacher_id')
                ->select();
            $list = objToArray($list) ?? [];

            foreach ($list as $key => $val){
                //获取一对一班级对应的老师列表
                $teacherIds = !empty($val['teacher_id']) ? explode(',',$val['teacher_id']) : [];
                if(!empty($teacherIds)){
                    $list[$key]['teacher_list'] = $this->manysotreLogic->teacherListByIds($teacherIds);
                }else{
                    $list[$key]['teacher_list'] = [];
                }
            }

            if(!empty($list)){
                $this->success('查询成功',$list);
            }
            $this->error('暂无数据');
        }
        $this->error('请求错误');
    }

    /**
     * 根据日期段返回是否允许预约一对一课程
     */
    public function dateReserve(){
        if($this->request->isPost()){
            $params = $this->request->param();
            //验证数据
            $params = $this->verifyData($params);

            $startDate = $params['start_date'] ?? '';
            $endDate = $params['end_date'] ?? '';
            if(empty($startDate) || empty($endDate)){
                $this->error('时间必须');
            }

            //日期数组
            $dateAry = rangeToDays($startDate,$endDate,true);
            //返回给前端的数据
            $res = [];
            //教师ID
            $teacherId = $params['teacher_id'] ?? 0;
            //教师约课规则
            $teacherRule = [];
            if(!empty($teacherId)){
                $teacherRule = $this->campusClassTeacherSettingLogic->rule($teacherId);
            }

            foreach ($dateAry as $date){
                $dateToTime = strtotime($date);
                //班级未指定教师，则默认不可约
                if(empty($teacherId)){
                    $res[] = [
                        'date' => $date,
                        'time' => $dateToTime,
                        'is_can' => false
                    ];
                }else{
                    $isCan = $this->campusClassTeacherSettingLogic->isCan($teacherId,$date,$teacherRule);
                    $res[] = [
                        'date' => $date,
                        'time' => $dateToTime,
                        'is_can' => $isCan
                    ];
                }
            }

            if(!empty($res)){
                $this->success('查询成功',$res);
            }
            $this->error('暂无数据',$res);
        }
        $this->error('请求错误');
    }

    /**
     * 一对一课程可选时间段
     */
    public function courseTimeSlot(){
        if($this->request->isPost()){
            $params = $this->request->param();
            //验证数据
            $params = $this->verifyData($params);

            $date = $params['date'] ?? '';
            if(empty($date)){
                $this->error('日期不能为空');
            }
            //课程ID
            $courseId = $params['course_id'] ?? 0;
            //班级ID
            $classId = $params['class_id'] ?? 0;
            if(empty($courseId)){
                $this->error('课程ID必须');
            }
            if(empty($classId)){
                $this->error('班级ID必须');
            }

            //教师ID
            $teacherId = $params['teacher_id'] ?? 0;
            if(empty($teacherId)){
                $this->error('请选择教师');
            }

            //获取班级详情
            $classInfo = $this->campusClassLogic->getInfo($params['shop_id'],$classId);
            $classHour = $classInfo['class_hour'] ?? 0;
            if($classHour == 0){
                $this->error('课时错误');
            }

            //获取教师的约课时间
            $teacherTime = $this->campusClassTeacherSettingLogic->getTimeSlot($teacherId,$date);
            //获取校区课程间隔时间
            $shopSettingInfo = $this->manystoreShopSettingLogic->ruleInfo($params['shop_id']);
            //返回给前端的数据
            $res = [];
            //间隔时间
            $intervalTime = 0;

            if($shopSettingInfo['appointment_one_type'] == 1){
                //系统生成间隔时间，根据班级课时间隔
                $intervalTime = $classHour * 3600;
            }else{
                //指定分钟生成间隔时间
                $intervalTime = $shopSettingInfo['appointment_one_num'] * 60;
            }

            if($intervalTime > 0 && !empty($teacherTime)){
                foreach ($teacherTime as $val){
                    $startTime = strtotime(date('Y-m-d '.$val['start_time']));
                    $endTime = strtotime(date('Y-m-d '.$val['end_time']));

                    $time = $startTime;
                    while($time < $endTime){
                        $res[] = [
                            'time' => date('H:i',$time),
                            'is_can' => true
                        ];
                        //如果剩余时间不满足一节课的时长，则不显示，例如老师授课时间为11:00-12:00，一节课时长为1.5小时，则该时间段不可预约
                        if(($time + $intervalTime) > $endTime){
                            array_pop($res);
                            break;
                        }
                        $time += $intervalTime;
                    }
                }
            }

            if(!empty($res)){
                $this->success('查询成功',$res);
            }
            $this->error('暂无数据');
        }
        $this->error('请求错误');
    }

    /**
     * 一对一课程约课
     * @throws Exception
     */
    public function reserve(){
        if($this->request->isPost()){
            $params = $this->request->param();
            //验证数据
            $params = $this->verifyData($params);

            $date = $params['date'] ?? '';
            if(empty($date)){
                $this->error('日期不能为空');
            }
            $week = date('w',strtotime($date));
            //课程ID
            $courseId = $params['course_id'] ?? 0;
            //班级ID
            $classId = $params['class_id'] ?? 0;
            if(empty($courseId)){
                $this->error('课程ID必须');
            }
            if(empty($classId)){
                $this->error('班级ID必须');
            }

            //教师ID
            $teacherId = $params['teacher_id'] ?? 0;
            if(empty($teacherId)){
                $this->error('请选择教师');
            }

            //约课时间
            $reserveTime = $params['reserve_time'] ?? '';
            if(empty($reserveTime)){
                $this->error('请选择约课时间');
            }

            //获取班级详情
            $classInfo = $this->campusClassLogic->getInfo($params['shop_id'],$classId);
            //获取后台排课详情
            $arrangingInfo = $this->campusClassCourseArrangingLogic->getInfoByClassId($classId);
            if(empty($arrangingInfo)){
                $this->error('该班级后台未排课');
            }

            //判断学员是否允许预约
            $reserveDate = strtotime(date('Y-m-d '.$reserveTime,strtotime($date)));
            $isExists = CampusClassCourseSignModel::where('teacher_id',$teacherId)
                ->where('start_time','<=',$reserveDate)
                ->where('end_time','>=',$reserveDate)
                ->count();
            if($isExists){
                $this->error('该时间已经有其他学员预约');
            }

            Db::startTrans();
            try {
                $startTime = strtotime(date('Y-m-d '.$reserveTime,strtotime($date)));
                $endTime = $startTime + $classInfo['class_hour'] * 3600;
                //判断是否有此课程排期
                $course_date = db('campus_class_course_date')->where('class_id',$classId)->where('start_time',$startTime)->where('end_time',$endTime)->find();
                if(!empty($course_date)){
                    $date_id = $course_date['id'];
                }else{
                    $date_id = db('campus_class_course_date')->insertGetId([
                       'shop_id'=> $params['shop_id'],
                       'class_id'=> $classId,
                       'week'=> $week,
                       'start_time'=> $startTime,
                       'start_time_txt'=> date('Y-m-d H:i:s',$startTime),
                       'end_time'=> $endTime,
                       'end_time_txt'=> date('Y-m-d H:i:s',$endTime),
                       'teacher_id'=> $teacherId,
                       'create_time'=>time()
                    ]);
                }
                //由于一对一课程无需排队，可直接添加排队成功记录
                $recordId = $this->campusClassDateRecordLogic->insert([
                    'shop_id'=> $params['shop_id'],
                    'user_id' => $params['user_id'],
                    'class_id' => $classId,
                    'date_id' => $date_id,
                    'status' => 1
                ]);
                //添加预约成功记录
                $this->campusClassCourseSignLogic->insert([
                    'shop_id'=> $params['shop_id'],
                    'a_id' => $arrangingInfo['id'],
                    'd_id' => $date_id,
                    'user_id' => $params['user_id'],
                    'class_id' => $classId,
                    'record_id' => $recordId,
                    'week' => $week,
                    'start_time' => $startTime,
                    'end_time' => $endTime,
                    'teacher_id' => $teacherId,
                ]);

                Db::commit();
                $this->success('预约成功');
            }catch (Exception $e){
                Db::rollback();
                $this->error('预约失败');
            }
        }
        $this->error('请求错误');
    }
}
